package com.atguigu.champter7.state;

import com.atguigu.beans.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Flink07_KeyedState_Aggregate {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 9999);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        env
                .socketTextStream("hadoop104", 9999)
                .map(line -> {
                    String[] watersensors = line.split(",");
                    return new WaterSensor(watersensors[0], Long.valueOf(watersensors[1]), Integer.valueOf(watersensors[2]));
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                //最大乱序程度
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                //分配水印
                                .withTimestampAssigner((element, ts) -> element.getTs())

                                .withIdleness(Duration.ofSeconds(5))//如果有个并行度长时间[自定义时间]未获取数据,将另一个并行度的水印给没有数据的并行度
                )
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private AggregatingState<WaterSensor, Double> vcavg;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        vcavg = getRuntimeContext().getAggregatingState(
                                new AggregatingStateDescriptor<WaterSensor, Avg, Double>("Vcavg",
                                        new AggregateFunction<WaterSensor,
                                                Avg,
                                                Double>() {
                                            @Override
                                            public Avg createAccumulator() {
                                                return new Avg();
                                            }

                                            @Override
                                            public Avg add(WaterSensor value, Avg acc) {
                                                acc.sum += value.getVc();
                                                acc.count++;
                                                return acc;
                                            }

                                            @Override
                                            public Double getResult(Avg acc) {
                                                return acc.avg(acc.sum, acc.count);
                                            }

                                            @Override
                                            public Avg merge(Avg a, Avg b) {
                                                return null;
                                            }
                                        }, Avg.class));

                    }

                    @Override
                    //计算每个传感器的平均水位
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {

                        vcavg.add(value);
                        out.collect(ctx.getCurrentKey() + " "+ vcavg.get());

                    }

                }).print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class Avg {
        public Integer sum = 0;
        public Long count = 0l;

        public Double avg(Integer sum, Long count) {
            return sum * 1.0 / count;
        }
    }
}
